<?php

if (!function_exists('toUnderScore')) {
    function toUnderScore($str)
    {
        $dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) {
            return '_'.strtolower($matchs[0]);
        }, $str);

        return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
    }
}

if (!function_exists('is_email')) {
    function is_email($email)
    {
        return preg_match('/[_a-zA-Z\d\-\.]+(@[_a-zA-Z\d\-\.]+\.[_a-zA-Z\d\-]+)+$/i', $email);
    }
}

if (!function_exists('is_tel')) {
    function is_tel($tel)
    {
        return preg_match('/^(((13[0-9]{1})|(15[0-35-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/', $tel);
    }
}

if (!function_exists('is_qq')) {
    function is_qq($qq)
    {
        return preg_match('/^[1-9]\d{4,12}$/', $qq);
    }
}

if (!function_exists('lang')) {
    function lang($code, $env = 'zh')
    {
        $code = (string) $code;
        $msgs = require __DIR__.'/../resources/lang/'.$env.'/code.php';

        if (array_key_exists($code, $msgs)) {
            return $msgs[$code];
        } else {
            return 'Undefined error code';
        }
    }
}

if (!function_exists('translate')) {
    function translate($en ,$env = 'zh')
    {
        $en = (string) $en;
        $trans = require __DIR__.'/../resources/lang/'.$env.'/translate.php';

        if (array_key_exists($en, $trans)) {
            return $trans[$en];
        } else {
            return '未翻译';
        }
    }
}

if (!function_exists('make_rank_code')) {
    function make_rank_code($type = 0, $len = 6)
    {
        if (0 == $type) {
            $codeSet = '123456789';
        } else {
            $codeSet = '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY';
        }

        $code = array();
        for ($i = 0; $i < $len; ++$i) {
            $code[$i] = $codeSet[mt_rand(0, strlen($codeSet) - 1)];
        }

        return implode('', $code);
    }
}

if (!function_exists('make_email_verfiy_token')) {
    function make_email_verfiy_token($email)
    {
        $date = date('Y-m-d H:i:s');
        $token = md5($email.$date.make_rank_code(0, 4));

        return $token;
    }
}

if (!function_exists('my_encrypt')) {
    function my_encrypt($txt, $key = null)
    {
        empty($key) && $key = 'Ha_Yii_Ro';
        $text = $key.'.'.$text;
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=_';
        $nh = rand(0, 64);
        $ch = $chars[$nh];
        $mdKey = md5($key.$ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = base64_encode($txt);
        $tmp = '';
        $j = 0;
        $k = 0;
        for ($i = 0; $i < strlen($txt); ++$i) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh + strpos($chars, $txt[$i]) + ord($mdKey[$k++])) % 64;
            $tmp .= $chars[$j];
        }

        return $ch.$tmp;
    }
}

if (!function_exists('my_decrypt')) {
    function my_decrypt($txt, $key = null)
    {
        empty($key) && $key = 'Ha_Yii_Ro';
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=_';
        $ch = $txt[0];
        $nh = strpos($chars, $ch);
        $mdKey = md5($key.$ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = substr($txt, 1);
        $tmp = '';
        $j = 0;
        $k = 0;
        for ($i = 0; $i < strlen($txt); ++$i) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]);
            while ($j < 0) {
                $j += 64;
            }
            $tmp .= $chars[$j];
        }
        $tmp = base64_decode($tmp);
        $res = explode('.', $tmp, 2);

        return ($res[0] != $key) ? false : $res[1];
    }
}

if (!function_exists('email_encrypt')) {
    function email_encrypt($string, $operation, $key = 'H_Y_R')
    {
        $key = md5($key);
        $key_length = strlen($key);
        $string = 'D' == $operation ? base64_decode($string) : substr(md5($string.$key), 0, 8).$string;
        $string_length = strlen($string);
        $rndkey = $box = array();
        $result = '';
        for ($i = 0; $i <= 255; ++$i) {
            $rndkey[$i] = ord($key[$i % $key_length]);
            $box[$i] = $i;
        }
        for ($j = $i = 0; $i < 256; ++$i) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for ($a = $j = $i = 0; $i < $string_length; ++$i) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }
        if ('D' == $operation) {
            if (substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) {
                return substr($result, 8);
            } else {
                return'';
            }
        } else {
            return str_replace('=', '', base64_encode($result));
        }
    }
}

if (!function_exists('model'))
{
    function model($name = ''){
        if (!$name)
        {
            throw new \Exception('Model name can not be empty');
        }
        $class = 'App\\Model\\Common\\'.ucwords($name);
        if (class_exists($class))
        {
            return new $class();
        }else
        {
            throw new \Exception($class.' class not found');
        }
    }
}


if (!function_exists('get_my_menu'))
{
    function get_my_menu($type = 'a')
    {
        if ($type === 'a')
        {
            $Menu = new App\Model\Common\AdminMenu;
            $menus = $Menu->getMyMenu(false);
            return $menus;
        } else
        {
            $Menu = new App\Model\Common\UserMenu;
            $menus = $Menu->getMyMenu(false);
            return $menus;
        }
    }
}

if (!function_exists('output')){
    function output($code = 0, $msg = '', $data = [])
    {
        if (is_object($msg)) {
            // $msg = $msg[0];
            foreach ($msg->all() as $message) {
                $msg = $message;
                break;
            }
        } elseif (!$msg && $code) {
            $msg = lang($code);
        }
    
        $resp = [];
        $resp['code'] = $code;
        $resp['msg'] = $msg;
        $resp['data'] = $data;
        $resp['time'] = time();
    
        return response()->json($resp);
    }
}

if (!function_exists('br_clear'))
{
    function br_clear($str)
    {
        return str_replace('<br />', '', $str);
    }
}